package cn.com.oidreams.wechat.robot.service;

import cn.com.oidreams.common.dto.RobotResponse;
import cn.com.oidreams.common.enums.ExceptionCode;
import cn.com.oidreams.common.utils.ReflectUtil;
import cn.com.oidreams.wechat.robot.entity.BaseRequest;
import cn.com.oidreams.wechat.robot.service.interfaces.IRobot;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

/***
 ** @category 请用一句话描述这个类的用途
 ** @author qing.yunhui
 ** @email: qingyh@glodon.com
 ** @createTime: 2021-12-15 11:51
 **/
public abstract class AbsWeXinTalkMessage {

    /**
     * <p>处理请求(子类需要根据不同场景实现)</p>
     * @param request
     * @return
     * */
    public abstract <T> String handle(BaseRequest<T> request, IRobot robot);

    /**
     * <p>处理请求</p>
     * @param request
     * @return
     * */
    public <T> RobotResponse doHandle(BaseRequest<T> request,IRobot robot) throws Exception {
        boolean pass = ReflectUtil.isRequiredPass(request);
        if(!pass){return new RobotResponse(ExceptionCode.VERIFICATION_FAILED);}
        String result = handle(request,robot);
        return JSONUtil.toBean(new JSONObject(result), RobotResponse.class);
    }

    /**
     * <p>发送消息</p>
     * @param request 待发送的消息
     * @return
     * */
    protected static <T> String send(BaseRequest<T> request,IRobot robot){
        try {
            String url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key="+robot.getCode();
            return HttpUtil.post(url, JSONUtil.toJsonStr(request));
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

}
